<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    :before-upload="beforeUpload"
    :http-request="handleUpload"
  >
    <img v-if="imageUrl || preview" :src="imageUrl || preview" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script>
import { ElMessage } from "element-plus";
import Cloud from "leancloud-storage";
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  props: ["preview"],
  data() {
    return {
      imageUrl: "",
    };
  },
  methods: {
    beforeUpload(rawFile) {
      console.log(rawFile);
      let typeArr = ["image/jpg", "image/jpeg", "image/png"];
      if (!typeArr.includes(rawFile.type)) {
        ElMessage.error("请上传jpg或png图片");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("Avatar picture size can not exceed 2MB!");
        return false;
      }
      return true;
    },
    // 自定义上传函数
    handleUpload(info) {
      // console.log("执行上传逻辑", info.file);
      // 将图片资源对象转化为base64变化
      getBase64(info.file, (base64) => {
        // console.log(base64);
        // this.imageUrl = base64;
        let cloudFile = new Cloud.File("admin-2206.png", { base64 }); //将base64转为了LeanCloud资源
        // 将资源提交至服务器
        cloudFile.save().then((res) => {
          console.log(res);
          let { url } = res.attributes;
          this.imageUrl = url;
          this.$emit("update:poster", url); //将后端给的图片链接传给父组件
        });
      });
    },
  },
};
</script>

<!-- <script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
</script> -->

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
